package models

import (
	"github.com/gocolly/colly"
	"github.com/tidwall/gjson"
	"strconv"
	"strings"

	"go-img/pkg/util"
)

func GetList(page int, size int) []string {
	images := make([]string, 0, size)
	url := "https://unsplash.com/napi/photos?page=" + strconv.Itoa(page) + "&per_page=" + strconv.Itoa(size)
	c := colly.NewCollector()
	var jsonString string
	c.OnHTML("img[src]", func(e *colly.HTMLElement) {
		link := e.Attr("src")
		if strings.Contains(link, "photo") {
			images = append(images, link)
		}
		c.Visit(e.Request.AbsoluteURL(link))
	})
	c.OnError(func(response *colly.Response, err error) {
		if err != nil {
			util.Error.Println(err)
		}
	})
	c.OnResponse(func(r *colly.Response) {
		jsonString = string(r.Body)
		//fmt.Printf(jsonString)
		if gjson.Valid(jsonString) {
			dataset := gjson.Get(jsonString, "#.urls.raw")
			for _, v := range dataset.Array() {
				images = append(images, v.String())
			}
		}

	})

	c.OnRequest(func(r *colly.Request) {
		//fmt.Println("Visiting", r.URL)
	})

	c.Visit(url)
	sum := len(images)
	util.Info.Println("本次爬取了" + strconv.Itoa(sum) + "个图片地址")
	return images
}

func GetSearch(keywords string, page int, size int) []string {
	url := "https://unsplash.com/napi/search/photos?query=" + keywords + "&xp=&per_page=" + strconv.Itoa(size) + "&page=" + strconv.Itoa(page)
	c := colly.NewCollector()
	images := make([]string, 0, size)
	var jsonString string
	c.OnError(func(response *colly.Response, err error) {
		if err != nil {
			util.Error.Println(err)
		}
	})
	c.OnResponse(func(r *colly.Response) {
		jsonString = string(r.Body)
		//fmt.Printf(jsonString)
		if gjson.Valid(jsonString) {
			dataset := gjson.Get(jsonString, "results.#.urls.raw")
			for _, v := range dataset.Array() {
				images = append(images, v.String())
			}
		}

	})
	c.Visit(url)
	sum := len(images)
	util.Info.Println("本次爬取了和" + keywords + "相关的" + strconv.Itoa(sum) + "个图片地址")
	return images
}
